package org.car.world.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.car.world.core.entily.UserTable;
import org.car.world.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.Avatar;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;

/**
 * @author zhangmister
 * @ClassName: MobileController
 * @Description: 手机页面controller
 * @date 2018年11月13日
 */
@Controller
public class MobileController {


    @Autowired
    UserService userService;

    @GetMapping("/index")
    public String index() {

        return "index";
    }

    @GetMapping("user")
    public String user() {

        return "user";
    }

    @GetMapping("gj")
    public String guanjia() {

        return "guanjia";
    }

    @GetMapping("login")
    public String login() {

        return "login";
    }


    @GetMapping("hongbao")
    public String hongbao() {

        return "hongbao";
    }

    @GetMapping("shoplist")
    public String shoplist() {

        return "shop_list";
    }

    //卖车
    @GetMapping("sellcar")
    public String sellcar() {
        return "sellcar";
    }


    //违章查询
    @GetMapping("peccancy")
    public String peccancy() {
        return "peccancy";
    }

    @GetMapping("codeLogin")
    public String codeLogin(HttpServletRequest request, Model model, HttpSession session) {

        try {
            UserTable user = null;
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            String accessToken = null,
                    openID = null;
            long tokenExpireIn = 0L;
            if ("".equals(accessTokenObj.getAccessToken())) {
                System.out.print("没有获取到响应参数");
            } else {
                accessToken = accessTokenObj.getAccessToken();
                tokenExpireIn = accessTokenObj.getExpireIn();
                OpenID openIDObj = new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                Avatar avatar = userInfoBean.getAvatar();
                user = userService.codeLogin(openID);
                if (user == null) {
                    user = new UserTable();
                    user.setUserNickname(userInfoBean.getNickname());
                    user.setUserHeadpor(avatar.getAvatarURL100());
                    user.setUserSex(userInfoBean.getGender().equals("男") ? 1 : 0);
                    user.setUserLogincode(openID);
                    user.setUserLoginway("QQ");
                    userService.insert(user);
                    session.setAttribute("user", user);
                } else {
                    session.setAttribute("user", user);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "user";
    }

    @GetMapping("qq")
    public String qq(HttpServletRequest request) {
        try {
            String url = new Oauth().getAuthorizeURL(request);
            return "redirect:" + url;
        } catch (QQConnectException e) {
            e.printStackTrace();
        }
        return "index";
    }

    @ResponseBody
    @GetMapping("loginout")
    public String loginout(HttpSession session) {
        try {
            session.removeAttribute("user");
        } catch (Exception e) {
            return "false";
        }
        return "true";
    }

    @ResponseBody
    @GetMapping("message")
    public String getMessage(@RequestParam(name = "phone", defaultValue = "") String phone) {
        // 短信应用SDK AppID
        int appid = 1400159342;
        // 短信应用SDK AppKey
        String appkey = "fc01a90c00259adf33241fdb3cd6aab2";
        // 需要发送短信的手机号码
        String[] phoneNumbers = {phone};
        // 短信模板ID，需要在短信应用中申请
        int templateId = 227801;
        //templateId7839对应的内容是"您的验证码是: {1}"
        // 签名
        String smsSign = "宋亚飞编程知识分享";
        int random = (int) ((Math.random() * 9 + 1) * 100000);
        Map<String, String> msg = new HashMap<String, String>(1);
        try {
            String[] params = {String.valueOf(random), "5"};
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumbers[0],
                    templateId, params, smsSign, "", "");
            System.out.println(result);
            msg.put("flag", "true");
            msg.put("code", String.valueOf(random));
        } catch (Exception e) {
            e.printStackTrace();
            msg.put("flag", "false");
        }
        return JSON.toJSONString(msg);
    }

    @ResponseBody
    @GetMapping("phoneLogin")
    public String phoneLogin(@RequestParam(name = "phone") String phone, HttpSession session) {
        try {
            UserTable user = null;
            user = userService.phoneLogin(phone);
            if (user == null) {
                user = new UserTable();
                user.setUserNickname(phone);
                user.setUserPhone(phone);
                //默认头像
                user.setUserHeadpor("http://www.17sucai.com/preview/1268063/2018-10-22/tour/images/user-003.png");
                user.setUserName(phone);
                userService.insert(user);
            }
            session.setAttribute("user", user);
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "false";
    }

    @ResponseBody
    @GetMapping("news")
    public String getNews(@RequestParam(name = "page") Integer page, @RequestParam(name = "postion") String postion) {
        String text = "";
        try {
            InputStream is = new URL("http://api01.idataapi.cn:8000/news/qihoo?kw=" + postion + "&site=qq.com&apikey=YGt8JfL7NvczCWtjDE69o4LGuCJ3XMVIhoS7Qr0S781HtFJubK9cWidwco2nvugU&pageToken=" + page + "").openStream();
            try {
                BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                StringBuilder sb = new StringBuilder();
                int cp;
                while ((cp = rd.read()) != -1) {
                    sb.append((char) cp);
                }
                text = sb.toString();
            } finally {
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;
    }
}
